package com.fengmi.cart.filter;

import cn.hutool.json.JSONUtil;
import com.fengmi.sso.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取登录用户信息
 */

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    //ThreadA
     private static ThreadLocal<SysUser> threadLocal = new ThreadLocal() ;

    //放行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user = request.getHeader("user");
        SysUser sysUser = JSONUtil.toBean(user, SysUser.class);
        threadLocal.set(sysUser);
        return true;
    }

    //请求执行完之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();   //1 保证数据不会串 2 防止内存泄露
    }

    public static SysUser getUserInfo(){
        return threadLocal.get();
    }

}
